import readline from 'readline'
import cliSpinners from 'cli-spinners'
import cliCursor from 'cli-cursor'
import { BufferListStream } from 'bl'

const spinners = cliSpinners.dots // 动画库
const text = 'loading' // 默认文本
const stream = process.stderr // 输出流
let frameIndex = 0 // 当前帧
const frames = spinners.frames // 每一帧的内容
const interval = spinners.interval // 每一帧的间隔
const mutedStream = new BufferListStream()

mutedStream.pipe(process.stdout) // 输入流缓冲到 BufferListStream
const rl = readline.createInterface({
	input: process.stdin, // 控制台输入流
	output: mutedStream // 输入流缓冲
})

function render() {
	clear()
	const renderText = frames[frameIndex] + ' ' + text
	stream.write(renderText)
	frameIndex = ++frameIndex % frames.length
}

function clear() {
	stream.cursorTo(0) // 光标移动到绝对位置
	// stream.moveCursor() // 光标移动相对位置
	stream.clearLine(1)
}

function stop() {
	clearInterval(timer)
	timer = undefined
	clear()
	frameIndex = 0
	cliCursor.show(stream)
	rl.close()
}

cliCursor.hide(stream)
let timer = setInterval(render, interval)

setTimeout(() => {
	stop()
}, 3000)

// stream.cursorTo(0)
// let x = 0,
// 	y = 0
// setInterval(() => {
// 	stream.moveCursor(++x, ++y)
// }, 1000)
